/*
 * author      : 吴中勤 
 * date        : 2019/3/13
 * description : TODO
 */

package org.wzq.learn;

import io.sentry.Sentry;
import io.sentry.SentryClient;
import io.sentry.SentryClientFactory;
import io.sentry.context.Context;
import io.sentry.event.BreadcrumbBuilder;
import io.sentry.event.UserBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class SentryService {
    private static final Logger logger = LoggerFactory.getLogger(SentryService.class);

    private SentryClient sentry;

    @Value("${spring.application.name}")
    private String serviceName;

    @Value("${sentry.dsn}")
    private String sentryDsn;

    @Value("${sentry.email}")
    private String sentryEmail;

    @PostConstruct
    public void init() {
        if (logger.isInfoEnabled()) logger.info("=====init sentryDsn=" + sentryDsn + ", sentryEmail=" + sentryEmail);
        // Sentry.init(sentryDsn);
        sentry = SentryClientFactory.sentryClient(sentryDsn);
    }

    /**
     * Examples that use the SentryClient instance directly.
     */
    public void sendAPIError(String xTraceId, Exception ex) {
        if (logger.isInfoEnabled()) logger.info("sentry.sendAPIError,  xTraceId=" + xTraceId);
        // String msg = "API_ERROR";

        // Retrieve the current context.
        Context context = sentry.getContext();

        // Record a breadcrumb in the current context. By default the last 100 breadcrumbs are kept.
        context.recordBreadcrumb(new BreadcrumbBuilder().setMessage(serviceName).build());

        // Set the user in the current context.
        context.setUser(new UserBuilder().setEmail(sentryEmail).build());
        Sentry.getContext().addExtra("serviceName", serviceName);

        // This sends a simple event to Sentry.
        context.addTag("x-trace-id", xTraceId);
        context.addTag("serviceName", serviceName);
//        sentry.sendMessage(msg);
        sentry.sendException(ex);
    }
}